<?php
/*
 +----------------------------------------------------------------------
 + Title        : RateLimitAspect 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2020/5/6 11:10
 + Last-time    : 2020/5/6 11:10+ 86187
 + Desc         : RateLimitAspect
 +----------------------------------------------------------------------
*/

namespace myAnnotation\rules;

use app\http\exception\ApiException;
use lib\MyRedis;
use myAnnotation\Annotation\RateLimit;

class RateLimitRule {
    /**
     * 接口限流注解实现
     *
     * @param RateLimit $rateLimit
     *
     * @author : Randy_chen
     * @Date   : 2020/5/6
     * @Time   : 11:11
     */
    function run(RateLimit $rateLimit) {
        $ip = request()->ip(1);

        $redis = MyRedis::getInstance();
        $scene = explode(',', $rateLimit->scene);
        $param = request()->param();
        $str = $param['version'] . ':' . $param['controller'] . ':' . $param['function'] . ':';
        if (in_array('ip', $scene)) {
            $key = 'currentLimit:ip:' . $str . $ip;
            if ($redis->lLen($key) >= $rateLimit->ipLimit) {
                throw new ApiException(11006);
            }
            $redis->lPush($key, 1);
            $redis->expire($key, 10);
        }
        if (in_array('user', $scene) && request()->uid) {
            $userKey = 'currentLimit:user:' . $str . request()->uid;
            if ($redis->lLen($userKey) >= $rateLimit->userLimit) {
                throw new ApiException(11007);
            }
            $redis->lPush($userKey, 1);
            $redis->expire($userKey, 10);
        }

    }
}